﻿package com.projects.xenia;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.concurrent.TimeUnit;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;

import com.projects.xenia.database_classes.SqlIntoXML;
import com.projects.xenia.database_classes.XmlIntoSql;
import com.projects.xenia.global_modules.MainGlobalModule;


import android.app.Activity;
import android.app.AlertDialog;
import android.app.Application;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnKeyListener;
import android.content.Intent;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Configuration;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager.OnActivityDestroyListener;

import android.telephony.CellLocation;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.Button;
import android.widget.SimpleAdapter;
import android.widget.TabHost;
import android.widget.Toast;

public class MainExchangeActivity extends Activity {

	private static String CurrentURLString;
	private static final String LocalURLString = "http://"+MainGlobalModule.SettingsCollection.get("LocalWebServiceURL");
	private static final String PrimaryURLString = "http://"+MainGlobalModule.SettingsCollection.get("PrimaryWebServiceURL");	
	private static final String SecondaryURLString = "http://"+MainGlobalModule.SettingsCollection.get("SecondaryWebServiceURL");	
	
	private static final int sChunk = 2048;
	
	private TabHost tabs;
	
	public RadioButton ConnectionState;	
	public Button LoadButton;
	public Button SendButton;
	public Button UpdateAppButton;
	public Button HistoryLoadButton;
	public Button ImageSendButton;
	public Button ImageLoadButton;
	public ListView ExchangeListLog;
	
	private XmlIntoSql xXmlIntoSql;
	
	private Message msg;
	private Bundle msg_data;
	
	private ProgressDialog pdh;
	private ProgressDialog pds;
	
	static ProgressDialog dl;
	
	private Context Ctx;
	
	private ArrayAdapter<CharSequence> ExchangeListLogAdapter;
	
	private String NewVersion; 
	
	private void SendData () {
		
		pdh = new ProgressDialog(this);
		pdh.setTitle("Обмен данными");	   
	    pdh.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
	    pdh.setMessage("Подготовка");
		pdh.setIndeterminate(true);
		pdh.setCancelable(false);		
		pdh.setCanceledOnTouchOutside(false);		
		pdh.setOnKeyListener(new OnKeyListener() {			
			@Override
			public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
				// TODO Auto-generated method stub
				return true;
			}
		});
		dl = pdh;
	    pdh.show();
	    
	    new Thread(new Runnable() 
    		{
	    	public void run() 
            	{
	    		
	    			String [] xTables = {"xdoc_orders_h","xdoc_orders_t","xdoc_orders_d","xdoc_orders_g","xdoc_orders_o","xdoc_orders_b","xdoc_payments_h","xdoc_payments_t","xdoc_payments_d","xdoc_returns_h","xdoc_returns_t","xdoc_returns_d","xdoc_blanks_h","xdoc_blanks_t","xdoc_gpslog","xdoc_photoreports_h","xdoc_photoreports_t","xdoc_photoreports_d","xdoc_readedmessages","xdoc_visits_h"};
	    			
	    			SqlIntoXML xSqlIntoXML = new SqlIntoXML ();
	    			
	    			if (xSqlIntoXML.TablesToXML(xTables)==true) {
	    				
	    				// internal data
					    LoadData(new String [] {"xdoc_orders_h","xdoc_payments_h","xdoc_returns_h","xdoc_blanks_h","xdoc_gpslog","xdoc_photoreports_h","xdoc_readedmessages","xdoc_visits_h"}, true);
					    
						// external data
						LoadData (new String [] {"xref_GoodsRests","xref_Debts","xref_PlanOfBrandSales","xref_Invoices","xref_Messages"},false);
						
						AddLogMessage ("Процедура обмена завершена !");
						
	    			}	
	    		
	    			else
	    			{
	    				AddLogMessage ("Сбой Процедуры отправки данных !");
	    			}
										
					ProgressHide();
					
            	}
    		}
    	).start();
		
	}
	
	private void UpdateProgramNext () {
		
		AddLogMessage ("Загрузка обновления ...");
		
		pdh = new ProgressDialog(this);
		pdh.setTitle("Загрузка обновления");	   
		pdh.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		pdh.setMessage("Подготовка");
		pdh.setIndeterminate(true);
		pdh.setCancelable(false);		
		pdh.setCanceledOnTouchOutside(false);		
		pdh.setOnKeyListener(new OnKeyListener() {			
		@Override
		public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {					
					return true;
				}
			});
		
			dl = pdh;
			pdh.show();

			new Thread(new Runnable() 
			{
				public void run() 
				
        			{					
        			
					File xapk = new File(String.format("%s/xenia.apk", MainGlobalModule.UpdatePath));				
					if (xapk.exists()){
						xapk.delete();
					}
			
					ProgressSetMax(1);
					ProgressSetValue(1);
					ProgressSetMessage("Запрос и загрузка apk файла");
			
					xXmlIntoSql = new XmlIntoSql();
					URL xUrl = GetWebServiceURL(CurrentURLString);						
					HttpURLConnection urlConnection;
			
					try {
				
						urlConnection = (HttpURLConnection) xUrl.openConnection();
						urlConnection.addRequestProperty("XeniaActionName", "GetApk");
						urlConnection.addRequestProperty("DeviceId",URLEncoder.encode(MainGlobalModule.SettingsCollection.get("DeviceId")));
						urlConnection.addRequestProperty("ManagerId",URLEncoder.encode(MainGlobalModule.SettingsCollection.get("ManagerId")));				
						urlConnection.setDoOutput(true);
						urlConnection.setChunkedStreamingMode(0);
						urlConnection.connect();
			
						// 	downloading		
						int length = 0;
						int BytesReadFromStream = 0;						
						byte[] buffer = new byte[sChunk];			
						ProgressSetMax(urlConnection.getContentLength());
						ProgressSetValue(0);
						
						if (urlConnection.getContentLength()==-1) {
							throw new Exception("No data !!!");
						}
						
						/// write response to .apk file
						InputStream uis = urlConnection.getInputStream();
						FileOutputStream tos = new FileOutputStream (xapk);			
						while ((length = uis.read(buffer, 0, sChunk)) != -1) {			
							BytesReadFromStream += length;
							ProgressSetValue(BytesReadFromStream);					
							tos.write(buffer, 0, length);				
						}						
				
						tos.flush();
						tos.close();		
						uis.close();
						urlConnection.disconnect();			
			
						File directory = new File(MainGlobalModule.StoragePath);				
						File ipFile = new File(directory, "ipconfig.txt");
						if (ipFile.exists()){
							ipFile.delete();	
						}
			
						FileWriter xFileWriter = new FileWriter(ipFile);
						xFileWriter.write(MainGlobalModule.SettingsCollection.get("PrimaryWebServiceURL"));
						xFileWriter.close();
			
			
						Intent intent = new Intent();
						intent.setAction(android.content.Intent.ACTION_VIEW);
						intent.setDataAndType(Uri.fromFile(xapk), "application/vnd.android.package-archive"); 

						startActivity(intent);
				
						File dbFile = new File(directory, "xenia.db");	    
						if (dbFile.exists()) {
							dbFile.delete();	
						}
			
					} catch (Exception e) {
						ProgressHide();
						AddLogMessage("Ошибка загрузки обновления !!!");
						e.printStackTrace();
					}
					
        		}
			}).start();
	}
	
	
	private void UpdateProgram () {
			
		
		AlertDialog.Builder adb = new AlertDialog.Builder(Ctx);    		
		adb.setTitle("Оновление!");
		adb.setMessage(String.format("Есть более новая версия %s желаете обновить ?%nВНИМАНИЕ !!! Все неотправленные данные будут потеряны.%nДля восстановления после обновления необходимо сделать %nЗагрузку данных и загрузку документов.",NewVersion));
		adb.setPositiveButton("Да(Реком.)", new AlertDialog.OnClickListener() {				
		@Override
			public void onClick(DialogInterface dialog, int which) {
				UpdateProgramNext ();
				dialog.dismiss();
			}
		}); 
		
		adb.setNegativeButton("Нет", new AlertDialog.OnClickListener() {				
			@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
				}
		});  

		adb.create().show();
			
	}
	
	private void AddLogMessage (String LogMsg) {
		
		
		final String pmsg = LogMsg;  
		ExchangeListLog.post(new Runnable() {
			@Override
			public void run() {
				ExchangeListLogAdapter.add(pmsg);
			}
		});		
		
	}
		
	private URL GetWebServiceURL (String URLString) {
		
		URL xUrl;
		
		try {
			xUrl = new URL(URLString.concat("/maWebService/XeniaPostHandler.ashx"));
		} catch (MalformedURLException e) {
			xUrl = null;
			e.printStackTrace();
		}
		
		return xUrl; 
	}
		
	private void SetCurrentURLString () {
		
		CurrentURLString = PrimaryURLString;
		
	}
		
	
	private String GetStringFromURL (URLConnection urlConnection) throws IOException  {		
		
		String decodedStringPart;
		
		BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
		StringBuilder decodedString = new StringBuilder();
		
		while ((decodedStringPart = in.readLine()) != null) {
			decodedString.append(decodedStringPart);
		}
		in.close();
		
		return decodedString.toString();
				
	}
	
	private void VersionCompare () throws NameNotFoundException {
				 
		String CurrentVersion = getPackageManager().getPackageInfo(getPackageName(), 0).versionName;
		if (!CurrentVersion.equals(NewVersion)) {
			UpdateAppButton.post(new Runnable() {
				@Override
				public void run() {
					UpdateAppButton.performClick();
				}
			});
		}; 
		
	}
	
	private void CheckConnection () {
		
		SetCurrentURLString ();
		
		new Thread(new Runnable() 
			{
				public void run() 
        			{	
					
					try { 
								
						URL xUrl = GetWebServiceURL(CurrentURLString);						
						HttpURLConnection urlConnection = (HttpURLConnection) xUrl.openConnection();
						urlConnection.addRequestProperty("XeniaActionName", "GetDeviceInfo");						
						urlConnection.addRequestProperty("DeviceId",URLEncoder.encode(MainGlobalModule.SettingsCollection.get("DeviceId")));						
						urlConnection.setDoOutput(true);
						urlConnection.setChunkedStreamingMode(0);
						urlConnection.connect();	
						
						String decodedString = GetStringFromURL (urlConnection);
						
						urlConnection.disconnect();
						 
					    String [] ReturnValues = decodedString.toString().split(";");
					    if (ReturnValues.length>=3) {					    	
					    	String Key = ReturnValues[1];
					    	String ManagerId = ReturnValues[0];
					    	String ManagerDescr = ReturnValues[2];	
					    	NewVersion = ReturnValues[3];					    	
					    	if (MainGlobalModule.md5(String.format("%s%s",MainGlobalModule.SettingsCollection.get("DeviceId"),"ALXAURMARXEN")).equals(Key)) {
					    		AddLogMessage(String.format("Подключен:%s", ManagerDescr));
						    	MainGlobalModule.SettingsCollection_Update("ManagerId",ManagerId);
						    	ProgressHide();
						    	VersionCompare ();
						    	return;
					    	}
					    }
					}
					
					catch (Exception e) {
						e.printStackTrace();						
						
					};
					finish ();
        			}
			}
		).start();
		
		
	}
		
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.exchange_form);
		
		LoadButton = (Button)findViewById(R.id.WebService_Loadbutton);
		LoadButton.setOnClickListener(new OnClickListener() {			
			@Override
			public void onClick(View v) {				
				FullDataload ();
			}
		});
		
		SendButton = (Button)findViewById(R.id.WebService_Sendbutton);
		SendButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				SendData();
			}
		});

		UpdateAppButton = (Button)findViewById(R.id.UpdateAppButton);
		UpdateAppButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				UpdateProgram ();
			}
		});
		
		HistoryLoadButton = (Button)findViewById(R.id.HistoryLoadButton);
		HistoryLoadButton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				HistoryLoad ();
			}
		});		
		
		ImageSendButton = (Button)findViewById(R.id.WebService_SendImages);
		ImageSendButton.setOnClickListener(new OnClickListener() {			
			@Override
			public void onClick(View v) {
				SendImages ();
			}
		}); 
		
		ImageLoadButton = (Button)findViewById(R.id.WebService_LoadImages);
		ImageLoadButton.setOnClickListener(new OnClickListener() {			
			@Override
			public void onClick(View v) {
				LoadImages (); 
			}
		});
		
		
		tabs = (TabHost) findViewById(android.R.id.tabhost);
		tabs.setup();
		
		TabHost.TabSpec spec;
		
		spec = tabs.newTabSpec("tag1");
		spec.setContent(R.id.tab1);
		spec.setIndicator("Обмен данными");
		tabs.addTab(spec);
		
		spec = tabs.newTabSpec("tag2");
		spec.setContent(R.id.tab2);
		spec.setIndicator("Системные функции");
		tabs.addTab(spec);
		
		
		ExchangeListLog = (ListView)findViewById(R.id.ExchangeLogList);
		ExchangeListLogAdapter = new ArrayAdapter<CharSequence> (this,R.layout.message_small,R.id.ExchangeLogLabel,new ArrayList(Arrays.asList("Подключение к серверу...")));
		ExchangeListLogAdapter.setNotifyOnChange(true);
		ExchangeListLog.setAdapter(ExchangeListLogAdapter);
		
		tabs.setCurrentTab(0);
		
		pds = new ProgressDialog(this);
	    pds.setTitle("Подключение");	   
	    pds.setProgressStyle(ProgressDialog.STYLE_SPINNER);
	    pds.setMessage("Авторизация устройства");
		pds.setIndeterminate(true);
		pds.setCancelable(false);
		pds.setCanceledOnTouchOutside(false);
		dl = pds; 
	    pds.show();
		
	    Ctx = this;
	    
		CheckConnection ();
		
	}
	
	static Handler xHandler = new Handler () {
	
	    public void handleMessage(Message lmsg) 
			{
	        	int msg_id = lmsg.arg1;
	        	int msg_value = lmsg.arg2;
	        	Bundle lmsg_data = lmsg.getData();
	        	
	        	switch (msg_id) {
				case -1:
					dl.dismiss();					
					break;
				case 0:
					dl.setIndeterminate(false);
					dl.setMax(msg_value);					
					break;					
				case 1:					
					dl.setIndeterminate(false);
					dl.setProgress(msg_value);					
					break;
				case 2:
					String MessageValue = lmsg_data.getString("MessageValue");
					Boolean IndeterminateValue = lmsg_data.getBoolean("IndeterminateValue");
					dl.setMessage(MessageValue);
					dl.setIndeterminate(IndeterminateValue);					
					break;
				default:
					break;
				}
	    }
	};
		
	private boolean LoadData (String [] xmlTables, Boolean xmlUpdate) {
		
		boolean _result = true;
		
		StringBuilder xStringBuilder = new StringBuilder ();
		for (String s:xmlTables) {
			xStringBuilder.append(s);
			xStringBuilder.append(";");
		}
		
		
		File TemporaryGzip = new File (String.format ("%s/%s",MainGlobalModule.TemporaryPath,"tempdata.gz"));
		if (TemporaryGzip.exists()) {
			TemporaryGzip.delete();
		}		
		 
		File TemporaryXMLFile = new File (String.format ("%s/%s",MainGlobalModule.TemporaryPath,"tempdata.xml"));
		if (TemporaryXMLFile.exists()) {
			TemporaryXMLFile.delete();
		}
		
		
		ProgressSetMax(1);
		ProgressSetValue(1);
		ProgressSetMessage("Запрос данных и получение данных");
		
		xXmlIntoSql = new XmlIntoSql();
		URL xUrl = GetWebServiceURL(CurrentURLString);						
		HttpURLConnection urlConnection;
		
		try {
			
						
			urlConnection = (HttpURLConnection) xUrl.openConnection();
			urlConnection.addRequestProperty("XeniaActionName", "GetSqlDataW");
			urlConnection.addRequestProperty("DeviceId",URLEncoder.encode(MainGlobalModule.SettingsCollection.get("DeviceId")));
			urlConnection.addRequestProperty("ManagerId",URLEncoder.encode(MainGlobalModule.SettingsCollection.get("ManagerId")));
			urlConnection.addRequestProperty("SqlTables",URLEncoder.encode(xStringBuilder.toString()));
			urlConnection.setDoOutput(true);
			urlConnection.setChunkedStreamingMode(0);
			urlConnection.connect();
		
			// downloading		
			int length = 0;
			int BytesReadFromStream = 0;						
			byte[] buffer = new byte[sChunk];			
			ProgressSetMax(urlConnection.getContentLength());
			ProgressSetValue(0);
			
			if (urlConnection.getContentLength()==1) {	
				_result = false;
				throw new Exception("No data !!!");
			}
			
			/// write response to .gz file
			InputStream uis = urlConnection.getInputStream();
			FileOutputStream tos = new FileOutputStream (TemporaryGzip);			
			while ((length = uis.read(buffer, 0, sChunk)) != -1) {			
					BytesReadFromStream += length;
					ProgressSetValue(BytesReadFromStream);					
					tos.write(buffer, 0, length);				
			}						
			
			tos.flush();
			tos.close();		
			uis.close();
			urlConnection.disconnect();
			
			/// decompressing to .xml file
			FileOutputStream xos = new FileOutputStream(TemporaryXMLFile);
			GZIPInputStream nis = new GZIPInputStream (new FileInputStream(TemporaryGzip));
			while ((length = nis.read(buffer, 0, sChunk)) != -1) {				
				xos.write(buffer, 0, length);				
			};
		
			xos.flush();
			xos.close();
			nis.close();
			
		} catch (Exception  e) {
			_result = false;
			AddLogMessage("Ошибка при загрузке и распаковке данных обмена !!!");
			e.printStackTrace();			
		}
		
		// parsing xml file and insert to sqlite
		try {
			xXmlIntoSql.xmlUpdate = xmlUpdate;
			xXmlIntoSql.XmlParseAndInsert(TemporaryXMLFile,xHandler);
			xXmlIntoSql = null;				
		} catch (Exception e) {
			_result = false;
			AddLogMessage("Ошибка при парсинге данных обмена !!!");
			e.printStackTrace();
		}
		
		if (TemporaryGzip.exists()){
			TemporaryGzip.delete();
		}
		
		if (TemporaryXMLFile.exists()){
			TemporaryXMLFile.delete();
		}
		
		return _result;
		
	}
		
	private void FullDataload () {
		
		AddLogMessage ("Старт процесса полной загрузки...");
		
		pdh = new ProgressDialog(this);
		pdh.setTitle("Полная загрузка данныx");	   
	    pdh.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
	    pdh.setMessage("Подготовка");
		pdh.setIndeterminate(true);
		pdh.setCancelable(false);		
		pdh.setCanceledOnTouchOutside(false);		
		pdh.setOnKeyListener(new OnKeyListener() {			
			@Override
			public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
				// TODO Auto-generated method stub
				return true;
			}
		});
		
		dl = pdh;
	    pdh.show();
	    
	    new Thread(new Runnable() 
    		{
	    	public void run() 
            	{	
	    			
					if (LoadData (localdata (),false)) {
						MainGlobalModule.SettingsCollection_Update("LastUpdate", String.valueOf(Calendar.getInstance().getTimeInMillis()));
					}
					
					MainGlobalModule.ConstantsCollection_Initialize ();
					ProgressHide();
					AddLogMessage ("Процедура полной загрузки завершена !");
					
					
            	}
    		}
    	).start();		
	    
	}


	private void CustomLoad (String [] Tables, boolean xmlUpdate) {
	
		pdh = new ProgressDialog(this);
		pdh.setTitle("Полная загрузка данныx");	   
		pdh.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		pdh.setMessage("Подготовка");
		pdh.setIndeterminate(true);
		pdh.setCancelable(false);		
		pdh.setCanceledOnTouchOutside(false);		
		pdh.setOnKeyListener(new OnKeyListener() {			
			@Override
			public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
				// TODO Auto-generated method stub
				return true;
			}
		});
	
		dl = pdh;
		pdh.show();	    
    
		final String [] lTables = Tables;
		final boolean lxmlUpdate = xmlUpdate;
    
		new Thread(new Runnable() 
			{
			public void run() 
    			{
					LoadData (lTables,lxmlUpdate);
					MainGlobalModule.ConstantsCollection_Initialize ();
					ProgressHide();					
					AddLogMessage ("Процедура выборочной загрузки завершена !");				
    			}
			}).start();
    
	}



	private void HistoryLoad () {
		AddLogMessage ("Старт процесса полной загрузки...");
		CustomLoad (new String []{"xdoc_orders_h_alt","xdoc_orders_t_alt","xdoc_orders_d_alt","xdoc_orders_o_alt","xdoc_orders_b_alt","xdoc_payments_h_alt","xdoc_payments_t_alt","xdoc_payments_d_alt","xdoc_returns_h_alt","xdoc_returns_t_alt","xdoc_returns_d_alt","xdoc_blanks_h_alt","xdoc_blanks_t_alt","xdoc_gpslog_alt","xdoc_photoreports_h_alt","xdoc_photoreports_t_alt"},false);
	
	}	
		
	private void ProgressHide () {
		
		msg = xHandler.obtainMessage();
		msg.arg1 = -1;
		msg.arg2 = 0;				
		xHandler.sendMessage(msg);
		
	}
	
	private void ProgressSetValue (int ProgressValue) {
		
		msg = xHandler.obtainMessage();				
		msg.arg1 = 1;				
		msg.arg2 = ProgressValue;				
		xHandler.sendMessage(msg);
		
	}
	
	private void ProgressSetMax (int ProgressValue) {
		
		msg = xHandler.obtainMessage();
		msg.arg1 = 0;
		msg.arg2 = ProgressValue;
		msg.setData(msg_data);
		xHandler.sendMessage(msg);
		
	}

	private void ProgressSetMessage (String MessageString) {
		
		msg_data = new Bundle ();
		msg_data.putString("MessageValue", MessageString);
		msg_data.putBoolean("IndeterminateValue", true);				
		msg = xHandler.obtainMessage();
		msg.arg1 = 2;
		msg.arg2 = 0;
		msg.setData(msg_data);
		xHandler.sendMessage(msg);
		
	}
	
	
	
	private ArrayList<String> GetImagesList () {
		
		ArrayList<String> ImageList;
		
		try {
				
			URL xUrl = GetWebServiceURL(CurrentURLString);
			HttpURLConnection urlConnection = (HttpURLConnection) xUrl.openConnection();
			urlConnection.setDoOutput(true);
			urlConnection.setChunkedStreamingMode(0);
			urlConnection.addRequestProperty("XeniaActionName", "GetImagesListW");
			urlConnection.connect();
			
			GZIPInputStream zis = new GZIPInputStream(urlConnection.getInputStream());
			StringBuffer content = new StringBuffer();		
			
			byte [] buffer = new byte[sChunk];
			int readedBytes = sChunk;
			while (readedBytes > 0) {
				readedBytes = zis.read(buffer, 0, sChunk);
				if (readedBytes>0)content.append(new String(buffer, 0, readedBytes));
				
			};
			
			
			zis.close();
			urlConnection.disconnect();		
			
			ImageList = new ArrayList<String>(Arrays.asList(content.toString().split(";")));
			
			return ImageList;
			
		} catch (Exception e) {
			e.printStackTrace();
		}		 
		
		return null;			
		
	}	
	
	private void DownloadImageNext (File ImageFile, String source, String FileId, Handler xhandler) {
		
		try {
			
			Message msg;
					
			String LocalCatalogURL = String.format ("%s/%s",CurrentURLString,source);
		
			// connecting
			URL xUrl = new URL(String.format("%s/%s", LocalCatalogURL,URLEncoder.encode(FileId)));
			URLConnection xURLConnection = xUrl.openConnection();
			
			xURLConnection.setConnectTimeout(5*60*1000);
			
			xURLConnection.setDoInput(true);
			InputStream xis =  xURLConnection.getInputStream();
		
			// downloading
		
			int BytesReadFromStream = 0;
			int BytesInStream = xURLConnection.getContentLength();
			int sChunk = 4096;
			byte[] buffer = new byte[sChunk];
			int length;
			
			ProgressSetMax(BytesInStream);
			ProgressSetValue(0);	
					
			FileOutputStream tso = new FileOutputStream (ImageFile);		
			
			while ((length = xis.read(buffer, 0, sChunk)) != -1) {
					BytesReadFromStream += length;
					msg = xhandler.obtainMessage();				
					msg.arg1 = 1;				
					msg.arg2 = BytesReadFromStream;				
					xhandler.sendMessage(msg);				
					tso.write(buffer, 0, length);				
				}
						
			xis.close();
			tso.flush();
			tso.close();		
			
			xUrl = null;
			xURLConnection = null;
			
		} catch (IOException e) {

			e.printStackTrace();
		};
		
	}	
	
	private void DownloadImage (String FileId,Long ImageSize, Handler xhandler) {
	
		File ImageFile = new File(String.format ("%s/%s",MainGlobalModule.GoodsImagesPath,FileId));	
		if (ImageFile.exists() && ImageFile.length()==ImageSize) {
			return;
		}
	
		DownloadImageNext (ImageFile, "GoodsImages", FileId, xhandler);	
	
		File ImageFileThubs = new File(String.format ("%s/%s",MainGlobalModule.GoodsImagesThumbsPath,FileId));	
		DownloadImageNext (ImageFileThubs, "GoodsImagesThumbs",FileId, xhandler);
	
	}

	private void LoadImages () {
	
		pdh = new ProgressDialog(Ctx);
		pdh.setTitle("Загрузка изображений");	   
		pdh.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		pdh.setMessage("Подготовка");
		pdh.setIndeterminate(true);
		pdh.setCancelable(false);		
		pdh.setCanceledOnTouchOutside(false);		
		pdh.setOnKeyListener(new OnKeyListener() {			
			@Override
			public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
				// TODO Auto-generated method stub
				return true;
			}
		});
	
		dl = pdh;
		pdh.show();
	
				
		new Thread (new Runnable() {				
			@Override
			public void run() {					
				ArrayList<String> ImageList = GetImagesList ();
				if  (ImageList!=null) {							
					for (int indx = 0;ImageList.size()>indx;indx++) {
						String idW [] = ImageList.get(indx).split(",");
						
						String FileId = idW[0];
						Long FileSize = Long.parseLong(idW[1]);				
						
						ProgressSetMessage(String.format ("%d из %d",indx,ImageList.size ()));
						DownloadImage (FileId,FileSize, xHandler);	
							
					}						
				}					
				ProgressHide();				
			}
		}).start();
	
	}
	
	

	class ImageSender extends AsyncTask<String, String, String> {
		
		@Override
		protected String doInBackground(String... arg0) {
			
			String decodedString = null;
			
			
				
				Cursor ImagesForSending = MainGlobalModule.DBE.rawQuery("select id from xdoc_PhotoReports_T where sended = 0",null);
			
				for (int i = 0;i<ImagesForSending.getCount();i++) {				
				
					ProgressSetMessage(String.format ("%d из %d",i,ImagesForSending.getCount()));
					ImagesForSending.moveToPosition(i);
				
					String _id = ImagesForSending.getString(0);
			
				
					decodedString = null;
					try {
						
						URL xUrl = GetWebServiceURL(CurrentURLString);
						HttpURLConnection urlConnection = (HttpURLConnection) xUrl.openConnection();
						urlConnection.setDoOutput(true);
						urlConnection.setChunkedStreamingMode(0);
				
						urlConnection.addRequestProperty("XeniaActionName", "InsertPhotoReport");
						urlConnection.addRequestProperty("Image_Name", _id);
							
						byte[] buffer = new byte[sChunk];
						int length;			
				
						String FullFileName = String.format("%s/%s.jpg", MainGlobalModule.PhotoReportsImagesPath,_id);
						FileInputStream fs = new FileInputStream (FullFileName);			  
						OutputStream os  = new BufferedOutputStream(urlConnection.getOutputStream());
				
						ProgressSetMax((int)new File(FullFileName).length());
						ProgressSetValue (0);
				
						int BytesWriteToStream = 0;
						while ((length = fs.read(buffer, 0, sChunk)) != -1) {
							os.write(buffer, 0, length);
							BytesWriteToStream += length;
							ProgressSetValue (BytesWriteToStream);
						};			
				
						fs.close();
						os.flush();
						os.close();			
							
						BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
						decodedString = in.readLine();
						in.close();				
						urlConnection.disconnect();
				
						if (decodedString!=null) {
							MainGlobalModule.DBE.execSQL(String.format("update xdoc_PhotoReports_T set sended = 1 where id = '%s'", decodedString));	
						}
						
					} catch (Exception e) {
						
						e.printStackTrace();
						
					}
				}
				
			return (decodedString);
			
		}
		
		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
				ProgressHide();
		}
		
	}
	

		
	private void SendImages () {
		
		pdh = new ProgressDialog(Ctx);
		pdh.setTitle("Отправка изображений");	   
	    pdh.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
	    pdh.setMessage("Подготовка");
		pdh.setIndeterminate(true);
		pdh.setCancelable(false);		
		pdh.setCanceledOnTouchOutside(false);		
		pdh.setOnKeyListener(new OnKeyListener() {			
			@Override
			public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
				return true;
			}
		});
		
		dl = pdh;
	    pdh.show();
	    
		ImageSender rl = new ImageSender();
		rl.execute();
		
	}
	
	
	String [] localdata () {
		
		ArrayList<String> _localdata = new  ArrayList<String> ();
		_localdata.add("xsys_MobileConstants");
		_localdata.add("xenum_AccType");
		_localdata.add("xenum_TypeDoc");
		_localdata.add("xenum_OrderNotes");
		_localdata.add("xenum_ReturnNotes");
		_localdata.add("xenum_PaymentNotes");
		_localdata.add("xenum_ReturnBases");
		_localdata.add("xref_CustomersGps");
		_localdata.add("xref_Blanks");
		_localdata.add("xref_BlanksStructure");
		_localdata.add("xref_PhotoReportTypes");
		_localdata.add("xref_OrdersGoodsDetails");
		_localdata.add("xref_Offers");
		_localdata.add("xref_Offers_Conditions");
		_localdata.add("xref_Offers_Conditions_Assortments");
		_localdata.add("xref_Offers_Conditions_Bonus");
		_localdata.add("xref_Reports");
		_localdata.add("xref_ReportsFields");
		_localdata.add("xref_Messages");
		_localdata.add("xref_TaskTemplates");		
		
		_localdata.add("xref_Goods");
		_localdata.add("xref_GoodsDivs");
		_localdata.add("xref_GoodsMeasures");
		_localdata.add("xref_Measures");
		_localdata.add("xref_Brands");
		_localdata.add("xref_Customers");
		_localdata.add("xref_Employees");
		_localdata.add("xref_Routes");
		_localdata.add("xref_Areas");
		_localdata.add("xref_Category");
		_localdata.add("xref_Firms");
		_localdata.add("xref_Departments");
		_localdata.add("xref_PriceCategory");
		_localdata.add("xref_CustomersCategory");
		_localdata.add("xref_GoodsPrices");
		_localdata.add("xref_GoodsBarcodes");
		_localdata.add("xref_GoodsRests");
		_localdata.add("xref_Debts");
		_localdata.add("xref_Debts_Details");
		_localdata.add("xref_CustomersDiscounts");
		_localdata.add("xref_CustomersAgreements");
		_localdata.add("xref_CustomersLicenses");
		_localdata.add("xref_StockInTrade");		
		_localdata.add("xref_CustomersStockInTrade");
		_localdata.add("xref_PlanOfBrandSales");
		_localdata.add("xref_Invoices");		
		_localdata.add("xref_AssortmentsList");
		_localdata.add("xref_AssortmentsItems");
		_localdata.add("xref_CustomersAssortments");
		_localdata.add("xref_VisitCauses");
		
		return _localdata.toArray(new String [_localdata.size()]);
		
	}
	
		
	
	
	
	
}